package org.crag.cafca.logic.time;

import java.util.Collection;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.crag.cafca.logic.time.Tag;

public class TimeLine 
{	
	private SortedSet<Event> events;
	private String familyName;

	
	public TimeLine(String familyName)
	{		
		this.events=new TreeSet<Event>(Event.getEventsComparator());
		this.familyName=familyName;
	}
	
	public void addEvent(Event event) 
	{
		event.setTimeLine(this);
		events.add(event);
	}	
	
	public void deleteEvent(Event event)
	{
		event.setTimeLine(null);
		events.remove(event);
	}
	
	public SortedSet<Event> getEvents()
	{
		return events;
	}
	
	/** 
	 * @param tag
	 * @return a SortedSet of events containing the single Tag tag
	 */
	public SortedSet<Event> getEventsWithTag(Tag tag)
	{
		SortedSet<Event> result = new TreeSet<Event>(Event.getEventsComparator());
		
		for (Event event : events)
		{
			if (event.containsTag(tag))
				result.add(event);
		}
		
		return result;
	}
	
	/**
	 * @param choice : boolean 
	 * @param tags
	 * @return a SortedSet of events containing every Tags of the Set. 
	 * @throws Exception if String is not match AND or OR.
	 */
	public SortedSet<Event> getEventsWithTag(Set<Tag> tags, boolean choice)
	{
		SortedSet<Event> result = new TreeSet<Event>(Event.getEventsComparator());
		
		if(choice)
			result = getEventsWithTags(tags); 
		else if(!choice)
			result = getEventsWithAtLeastOneTag(tags); 
		else
			result.clear();
		
		return result; 
		
	}
	
	private SortedSet<Event> getEventsWithTags(Set<Tag> tags)
	{
		SortedSet<Event> result = new TreeSet<Event>(Event.getEventsComparator());
		
		for(Event event : this.events)
		{
			boolean shouldBeAdded = true;
				
			for(Tag tag : tags)
			{
				if(!event.containsTag(tag))
					shouldBeAdded = false;
			}
			
			if(shouldBeAdded)
				result.add((Event) event); 
		}
		
		return result; 
	}
	
	private SortedSet<Event> getEventsWithAtLeastOneTag(Set<Tag> tags)
	{
		SortedSet<Event> result = new TreeSet<Event>(Event.getEventsComparator());
		
		for(Event event : this.events)
		{
			for(Tag tag : tags)
			{
				if(event.containsTag(tag))
				{
					result.add(event);
					break;
				}
			}
		}
				
		return result;
	}

	public String getFamilyName() 
	{
		return familyName;
	}

	public void setFamilyName(String familyName) 
	{
		this.familyName = familyName;
	}

	public void addEvents(Collection<Event> events) 
	{
		for (Event event:events)
		{
			event.setTimeLine(this);
		}
		this.events.addAll(events);
	}

	public Event getEventFromId(int id) 
	{
		for (Event event:events)
		{
			if (event.getId()==id)
				return event;
		}
		
		return null;
	}
} 
